//
//  ST_EditBarrageView.swift
//  BTVideo
//
//  Created by DouLei on 2019/7/16.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyUserDefaults
import SwifterSwift
import SwiftyUserDefaults

let BARRAGE_MAX_LENGTH = 30

enum ST_BarrageDirection:Int {
    case top = 1,middle = 2,bottom = 3
}

struct ST_EditBarrageModel {
    var text:String
    var color:UIColor
    var direction:ST_BarrageDirection
}

class ST_EditBarrageView: UIView,UITextViewDelegate {
    
    static let input_state_height = 100.cgFloat
    
    static let Height = 100.cgFloat
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = Color.white
        addSubview(top_direction_btn)
        addSubview(medium_direction_btn)
        addSubview(bottom_direction_btn)
        addSubview(select_color_btn)
        addSubview(textView)
        
        top_direction_btn.snp.makeConstraints { (make) in
            
            make.left.equalTo(self).offset(15)
            make.top.equalTo(self).offset(19)
            make.width.equalTo(28)
            make.height.equalTo(22)
        }
        
        medium_direction_btn.snp.makeConstraints { (make) in
            
            make.left.equalToSuperview().offset(63)
            
            make.top.width.height.equalTo(top_direction_btn)
        }
        
        bottom_direction_btn.snp.makeConstraints { (make) in
            
            make.left.equalToSuperview().offset(111)
            
            make.top.width.height.equalTo(top_direction_btn)
        }
        
        select_color_btn.snp.makeConstraints { (make) in
            
            make.left.equalToSuperview().offset(159)
            
            make.top.width.height.equalTo(top_direction_btn)
            
        }
        
        textView.snp.makeConstraints { (make) in
            make.left.equalTo(self).offset(15)
            make.right.equalTo(self).offset(-15)
            make.top.equalTo(select_color_btn.snp.bottom).offset(18)
            make.height.equalTo(32)
        }
        self.addSubview(text_placeholder_label)
        text_placeholder_label.snp.makeConstraints { (make) in
            make.top.bottom.right.equalTo(textView)
            make.left.equalTo(textView).offset(10)
        }
        
        self.addSubview(color_list_view)
        color_list_view.snp.makeConstraints { (make) in
            make.width.equalTo(180)
            make.height.equalTo(22)
            make.centerY.equalTo(top_direction_btn)
            make.left.equalToSuperview().offset(110)
        }
        
        self.addSubview(barrageStatusBtn)
        barrageStatusBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(top_direction_btn)
            make.width.equalTo(40)
            make.height.equalTo(22)
        }
        
        let colorBtnWidth = 30.cgFloat
        
        let colorBtnGap = 20.cgFloat
        
        for (i,item) in colorArray.enumerated() {
            
            let colorBtn = UIButton.init(type: UIButton.ButtonType.custom)
            
            colorBtn.cornerRadius = 5
            
            colorBtn.backgroundColor = item
            
            colorBtn.setImage(ST_ImageUtils.imageName("勾"), for: UIControl.State.selected)
            
            colorBtn.tag = self.color_btn_base_tag + i
            
            colorBtn.addTarget(self, action: #selector(select_color_hanlde(sender:)), for: UIControl.Event.touchUpInside)
            
            color_list_view.addSubview(colorBtn)
            
            colorBtn.snp.makeConstraints { (make) in
                make.left.equalTo(color_list_view).offset(i.cgFloat*(colorBtnWidth+colorBtnGap))
                make.width.equalTo(colorBtnWidth)
                make.bottom.top.equalToSuperview()
            }
        }
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboard_will_show),
            name: UIResponder.keyboardWillShowNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboard_will_hidden(_:)),
            name: UIResponder.keyboardWillHideNotification,
            object: nil
        )
        
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
        
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

//    MARK: - keyboard event
    @objc func keyboard_will_show(_ notification: Notification) {
        
        if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
        
            let keyboardRectangle = keyboardFrame.cgRectValue
            
            let keyboard_height = keyboardRectangle.height
            
            print("当前Keyboard Height：\(keyboard_height)")
            
            self.y = ScreenHeight - keyboard_height - ST_EditBarrageView.input_state_height
            
        }
    }
    
    @objc func keyboard_will_hidden(_ notification: Notification) {
    
        self.y = ScreenHeight - ST_EditBarrageView.Height
        
    }
//    MARK: - Properties
    
    lazy var last_selected_btn:UIButton = {
       return top_direction_btn
    }()
    
    lazy var top_direction_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)

        control.setImageForAllStates(ST_ImageUtils.imageName("editBarrage_顶部默认")!)
        
        control.setImage(ST_ImageUtils.imageName("editBarrage_顶部选中")!, for: UIControl.State.selected)
        
//        control.backgroundColor = Color.random
        
        control.isSelected = true
        
        control.addTarget(self, action: #selector(click(sender:)), for: UIControl.Event.touchUpInside)

        return control
    }()
    
    lazy var medium_direction_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("editBarrage_中部默认")!)
        
        control.setImage(ST_ImageUtils.imageName("editBarrage_中部选中")!, for: UIControl.State.selected)
        
        control.addTarget(self, action: #selector(click(sender:)), for: UIControl.Event.touchUpInside)
        
        
        return control
    }()
    
    lazy var bottom_direction_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("editBarrage_底部默认")!)
        
        control.setImage(ST_ImageUtils.imageName("editBarrage_底部选中")!, for: UIControl.State.selected)
        
        control.addTarget(self, action: #selector(click(sender:)), for: UIControl.Event.touchUpInside)
        
        
        return control
    }()
    
    
    lazy var select_color_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("editBarrage_颜色默认")!)
        
        control.addTarget(self, action: #selector(show_select_color_list), for: UIControl.Event.touchUpInside)
        
        
        return control
    }()
    
    
    lazy var textView:UITextView = {
        
        let control = UITextView()
        control.cornerRadius = 18
        control.contentInset = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.backgroundColor = Color.init(hexString: "#F5F5F5")
        control.returnKeyType = .send
        control.delegate = self
        control.enablesReturnKeyAutomatically = true
        return control
    }()
    
    
    lazy var text_placeholder_label:UILabel = {
       let control = UILabel()
        control.text = "写下想说的话，留言给TA(30字以内)"
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.textColor = UIColor.init(hexString: "#999999")
        return control
    }()
    
    lazy var barrageStatusBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("IndexItem_icon_弹幕关")!)
        
        control.setImage(ST_ImageUtils.imageName("IndexItem_icon_弹幕开")!, for: UIControl.State.selected)
        
        control.isSelected = !Defaults[.BThiddenBarrageHomePage]
        
        control.addTarget(self, action: #selector(display_barrage_handle(sender:)), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    private let color_btn_base_tag = 1045
        
    private let colorArray = BarrageColorArray
    
    private lazy var color_list_view:UIView = {
       
        let control = UIView()
        
        control.isHidden = true
        
        control.backgroundColor = Color.white
        
        return control
        
    }()
    
    
    
    /**
     默认展示顶部，白色
     */
    private var currentBarrage = ST_EditBarrageModel.init(text: "", color: UIColor.white, direction: ST_BarrageDirection.top)
    
    fileprivate var randomColorOper = true
    
    var sendBlock:((ST_EditBarrageModel)->())?
    
    //    MARK: - Event
    var display_barrage_closure:((Bool)->())?
    
    @objc func display_barrage_handle(sender:UIButton){
        
        sender.isSelected = !sender.isSelected
        
        display_barrage_closure?(sender.isSelected)
        
    }
    
    var last_selected_color:UIButton?
    
    @objc func select_color_hanlde(sender:UIButton){
        
        
        if sender.isSelected {
            self.currentBarrage.color = Color.white
            last_selected_color?.isSelected = false
            last_selected_color = nil
            randomColorOper = true
        }else{
            
            last_selected_color?.isSelected = false
            
            sender.isSelected = true
            
            last_selected_color = sender
            
            self.currentBarrage.color = colorArray[sender.tag-self.color_btn_base_tag]
            randomColorOper = false
        }
    }
    
    @objc func click(sender:UIButton){
        
        if sender.isSelected {
            return
        }
        if [medium_direction_btn,bottom_direction_btn].contains(sender) {
         
            return
        }
        
        
        self.last_selected_btn.isSelected = false
        sender.isSelected = true
        self.last_selected_btn = sender
        
        switch sender {
        case top_direction_btn:
            self.currentBarrage.direction = .top
        case medium_direction_btn:
            self.currentBarrage.direction = .middle
        default:
            
            self.currentBarrage.direction = .bottom
            break
        }
        
    }
    
    @objc func show_select_color_list(){
        
        
       
        
        select_color_btn.isSelected = !select_color_btn.isSelected
        
        if select_color_btn.isSelected{
            
            for item in [top_direction_btn,medium_direction_btn,bottom_direction_btn]{
                
                if item == self.last_selected_btn{
                    
                    UIView.animate(withDuration: 0.25, animations: {
                        
                        item.snp.updateConstraints({ (make) in
                            make.left.equalToSuperview().offset(15)
                        })
                        
                        self.select_color_btn.snp.updateConstraints { (make) in
                            make.left.equalToSuperview().offset(63)
                        }
                        self.layoutIfNeeded()
                        
                    }) { (f) in
                        self.color_list_view.isHidden = false
                    }
                }else{
                    item.alpha = 0
                }
            }
        } else{
            
            self.color_list_view.isHidden = true
            
            UIView.animate(withDuration: 0.25, animations: {
                
                self.top_direction_btn.alpha = 1
                
               
            }) { (f) in
                
            }
            
            UIView.animate(withDuration: 0.55, animations: {
                
                self.medium_direction_btn.alpha = 1
                
                
            }) { (f) in
                
            }
            
            UIView.animate(withDuration: 0.75, animations: {
                
                self.bottom_direction_btn.alpha = 1
                
                
            }) { (f) in
                
            }
            
            
            
            UIView.animate(withDuration: 0.25, animations: {
                
                self.top_direction_btn.snp.updateConstraints { (make) in
                    
                    make.left.equalTo(self).offset(15)
                    
                }
                
                self.medium_direction_btn.snp.updateConstraints { (make) in
                    
                    make.left.equalToSuperview().offset(63)
                    
                }
                
                self.bottom_direction_btn.snp.updateConstraints { (make) in
                    
                    make.left.equalToSuperview().offset(111)
                    
                }
                
                self.select_color_btn.snp.updateConstraints { (make) in
                    
                    make.left.equalToSuperview().offset(159)
                }
              
                self.layoutIfNeeded()
                
            }) { (f) in
                
                
            }
            
            
            
            
            
        }
        
        
        
        
        
        
    }
    
    
//    MARK: - Delegate
    func textViewDidChange(_ textView: UITextView) {
        
        text_placeholder_label.isHidden = !textView.text.isEmpty
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if (text == "\n") {
            
            currentBarrage.text = textView.text
            
            textView.resignFirstResponder()
            
            textView.text = ""
            
            self.text_placeholder_label.isHidden = false
            
//            默认添加随机色
            if randomColorOper {
                
                currentBarrage.color = colorArray.randomElement()!
            }
            
            
            self.sendBlock?(currentBarrage)
            
            return false
        }
        
        let currentString: NSString = textView.text! as NSString
        
        let newString: NSString =
            currentString.replacingCharacters(in: range, with: text) as NSString
        
        return newString.length <= BARRAGE_MAX_LENGTH
    }
}
